package com.film.service.impl.movie;

import com.alibaba.fastjson.JSONObject;
import com.film.service.movie.SearchMovieService;
import com.film.utils.MySqlConnection;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

@Service
public class SearchMovieServiceImpl implements SearchMovieService {
    @Override
    public JSONObject search(String movieName) throws SQLException {
        JSONObject resp = new JSONObject();
        List<JSONObject> items = new LinkedList<>();
        String sql = "select * from Movie where name = " + "'" + movieName + "'";
        Statement stmt = MySqlConnection.connect.createStatement();
        System.out.println(sql);
        ResultSet resultSet = stmt.executeQuery(sql);
        if (!resultSet.isBeforeFirst()) { //resultSet为空
            resp.put("error_message", "未查找到该电影");
            return resp;
        }
        JSONObject item = new JSONObject();
        if (resultSet.next()) {
            String movieId = resultSet.getString("id");
            String name = resultSet.getString("name");
            String imgUrl = resultSet.getString("image");
            Integer stars = resultSet.getInt("stars");
            HashMap<String, String> inf = new HashMap<>();
            item.put("name", name);
            item.put("imgUrl", imgUrl);
            item.put("stars", String.valueOf(stars));
            item.put("movieId", movieId);
            item.put("comments", new ArrayList<JSONObject>());
            items.add(item);
        }

        String commentSql = "select comment, username, photo_url from Movie, Movie_Comments, User where Movie.id=Movie_Comments.movie_id and Movie_Comments.commentator_id = User.id and Movie.name = " + "'" + movieName + "'";
        ResultSet commentsResult = stmt.executeQuery(commentSql);
        while (commentsResult.next()) {
            JSONObject comments = new JSONObject();
            String comment = commentsResult.getString("comment");
            String username = commentsResult.getString("username");
            String avatarUrl = commentsResult.getString("photo_url");
            comments.put("comment", comment);
            comments.put("name", username);
            comments.put("avatarUrl", avatarUrl);
            ArrayList<JSONObject> commentsArray = (ArrayList<JSONObject>) item.get("comments");
            commentsArray.add(comments);
        }

        resp.put("movies", items);
        resp.put("movies_count", items.size());
        resultSet.close();
        stmt.close();
        return resp;
    }
}
